const WebSocket = require('ws');
const controller = require('./controller/index');
const logger = require('./util/log')
const device = require('./util/device')

const WebSocketServer = WebSocket.Server;

let port = 4000;
const TAG  = '[SERVER]'

if (process.env.NODE_ENV === 'development') {
    console.log("Running in development mode");
    port = 4001;
}

const ws = new WebSocketServer({
    port
})

console.log(`ws server start at port ${port}`)


ws.on('connection', function (socket, request) {
    const ip = request.socket.remoteAddress;

    logger.log(TAG, `Client connected: ${ip}, ${device.getReqIDs(request)}`);

    socket.on('message', function (buffer, isBinary) {
        controller.handleClient(socket, request, buffer, isBinary);
    });
});